<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;

use app\admin\model\Image;
use app\admin\model\Specialtopiccontent;

use think\Db;
use think\Request;

class Specialtopic extends Base
{
    public function _initialize() {
        parent::_initialize();

        $this->redirect = 'admin/specialtopic/index';
        $this->defaultOrder = 'sorting';
        $defaultWhere = $this->getDefaultWhere();
        $this->defaultWhere = $defaultWhere;

        $this->searchFields = [
            'title' => [
                'label'     => '专题名称',
                'field'     => 'title',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'

            ],
        ];
        $this->defaultOrder = 'sorting ASC';
    }

    public function index(){

        return parent::index();
    }

    public function add(Request $request) {

        return parent::add($request);
    }

    public function addPost(Request $request, $redirect = '') {
        $redirect = $this->redirect;

        return parent::addPost($request, $redirect);
    }

    public function edit(Request $request) {

        return parent::edit($request);
    }

    public function editPost(Request $request, $redirect = ''){
        $redirect = $this->redirect;

        return parent::editPost($request, $redirect);
    }

    /**
     * Delete
     */
    public function delete(){
        $model = model($this->model);

        $request = $this->request;
        $id = $request->param('id');

        if($id){
            $specialtopiccontent = Specialtopiccontent::where(['specialtopicId' => $id])->select();
            if($specialtopiccontent) {
                return $this->error('该专题有专题内容，请先去删除专题内容！');
            }

            Db::startTrans();
            try{
                $result = $model->where('id', $id)->delete();
                if($result !== false){
                    // TODO 关联删除
                    // 删除专题分类
                    $specialtopictypeDB = db('specialtopictype');
                    $specialtopictype = $specialtopictypeDB->where(['specialtopicId' => $id])->delete();
                    if($specialtopictype === false){
                        Db::rollback();
                        return $this->error('删除专题分类失败！', 'admin/' . strtolower($this->model) . '/index');
                    }

                    // Query执行后的操作
                    $model->_after_delete($id);

                    $logInfo = $this->admin->name . '删除了1条' . $this->model . '数据。';
                    Common::adminLog($request, $logInfo);

                    Db::commit();
                    return $this->success('删除成功！', 'admin/' . strtolower($this->model) . '/index');
                }else{
                    Db::rollback();
                    return $this->error('删除失败！', 'admin/' . strtolower($this->model) . '/index');
                }
            }catch (Exception $e){
                Db::rollback();
                return $this->error($e->getMessage());
            }
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if(isset($filter['cityId']) && $filter['cityId']){
                $where['cityId'] = $filter['cityId'];
            }
            if(isset($filter['xianId']) && $filter['xianId']){
                $where['xianId'] = $filter['xianId'];
            }
            if(isset($filter['townId']) && $filter['townId']){
                $where['townId'] = $filter['townId'];
            }
            if(isset($filter['villageId']) && $filter['villageId']){
                $where['villageId'] = $filter['villageId'];
            }
            if(isset($filter['typeId']) && $filter['typeId']){
                $where['typeId'] = $filter['typeId'];
            }
            if(isset($filter['contentType']) && $filter['contentType']){
                $where['contentType'] = $filter['contentType'];
            }
            if(isset($filter['title']) && $filter['title']){
                $where['title'] = ['like', '%'.$filter['title'].'%'];
            }
        }

        return $where;
    }

    /**
     * 专题分类
     */
    public function getTypeDatalist() {
        $request = $this->request;
        $param = $request->param();
        $model = db('specialtopictype');

        // 每页起始条数
        $start = $param['start'];
        // 每页显示条数
        $length = $param['length'];

        $where = [
            'specialtopicId' => $param['id']
        ];
        $list = $model->where($where)->limit($start, $length)->select();
        $count = $model->where($where)->count();
        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];

        return json($result);
    }

    /**
     * 保存专题分类
     */
    public function saveType() {
        $request = $this->request;
        $model = model('specialtopictype');

        //save data
        if ($request->isAjax()) {
            $data = $request->param();

            if(!$data['specialtopicId']){
                return json(['code' => 0, 'msg' => '保存失败！']);
            }

            if(isset($data['id']) && $data['id']){
                $data['updateDate'] = time();
                $data['updateOper'] = $this->admin->id;

                $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

                if($result !== false) {
                    // Query执行后的操作
                    $model->_after_update($data);

                    // 写入日志
                    $logInfo = $this->admin->name . '更新了一条专题分类数据。';
                    Common::adminLog($request, $logInfo);

                    return json(['code' => 1, 'msg' => '保存成功！', 'id' => $data['id']]);
                } else {
                    return json(['code' => 0, 'msg' => $model->getError()]);
                }
            }

            // Insert data
            $data['id'] = Helper::getUUID();
            $data['createDate'] = time();
            $data['createOper'] = $this->admin->id;

            $result = $model->save($data);

            if($result !== false) {
                // 写入日志
                $logInfo = $this->admin->name . '添加了一条专题分类数据。';
                Common::adminLog($request, $logInfo);

                return json(['code' => 1, 'msg' => '添加成功！', 'id' => $data['id']]);
            } else {
                return json(['code' => 0, 'msg' => $model->getError()]);
            }
        } else {
            return json(['code' => 0, 'msg' => '请求方式不正确！']);
        }
    }

    /**
     * 删除专题分类
     */
    public function delType() {
        $model = model('specialtopictype');

        $request = $this->request;
        $id = $request->param('id');

        // 删除一条
        $info = $model->find(['id', $id]);
        if(!$info){
            return json(['code' => 0, 'msg' => 'error']);
        }
        $result = $model->where('id', $id)->delete();

        if($result !== false){
            $logInfo = $this->admin->name . '删除了1条专题分类数据。';
            Common::adminLog($request, $logInfo);
        }

        if($result !== false){
            return json(['code' => 1, 'msg' => '删除成功！']);
        }else{
            return json(['code' => 0, 'msg' => '删除失败']);
        }
    }

}
